<template>
  <div class="app-container">
    <el-card style="margin: 15px; min-height: calc(100vh - 111px);">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="学号" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="studentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="学号" align="center" prop="studentId" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="所属宿舍" align="center" prop="dormName">
        <template slot-scope="scope">
          {{
            scope.row.dormName == null || scope.row.dormName == ""
              ? "未分配宿舍"
              : scope.row.dormName
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="form.id != null">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number
            v-model="form.age"
            :min="1"
            :max="150"
            label="请输入年龄"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="form.gender" label="男">男</el-radio>
          <el-radio v-model="form.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="所属宿舍" prop="dormitoryId">
          <el-select
            v-model="form.dormitoryId"
            filterable
            placeholder="请选择所属宿舍"
          >
            <el-option
              v-for="item in dormitoryList"
              :key="item.id"
              :label="`${item.buildingName}-${item.dormNumber}`"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  listStudent,
  getStudent,
  delStudent,
  addStudent,
  updateStudent,
} from "@/api/student";
import { getAllDormitory } from "@/api/dorm";

export default {
  name: "StudentView",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 学生信息表格数据
      studentList: [],
      /* //楼栋信息数据
      buildingList: [], */
      //宿舍信息数据
      dormitoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        name: null,
        dormitoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2到10位的姓名", trigger: "blur" },
        ],
        studentId: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          { min: 13, max: 13, message: "请输入13位学号", trigger: "blur" },
        ],
        password: [
          { required: false, message: "密码不能为空", trigger: "blur" },
          { max: 16, message: "请输入不超过16位的密码", trigger: "blur" },
        ],
        age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" },
        ],
        dormitoryId: [
          { required: true, message: "所属宿舍不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    /*     this.loadAllBuilding(); */
    this.loadAllDorm();
  },
  methods: {
    // 重置表单验证状态
    resetFormValidation() {
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then((response) => {
        if(response.data.code === 200){
          this.studentList = response.data.data.rows;
          this.total = response.data.data.total;
          this.loading = false;
        }else{
          this.$message({
                type: "warning",
                message: response.data.msg,
              });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        studentId: null,
        password: null,
        age: null,
        gender: null,
        dormitoryId: null,
        roleId: null,
        createTime: null,
        updateTime: null,
      };
      this.resetFormValidation(); // 重置表单验证状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStudent(id).then((response) => {
        if(response.data.code !== 200){
          this.$message({
                type: "warning",
                message: response.data.msg,
              });
          return;
        }
        this.form = response.data.data;
        this.open = true;
        this.title = "修改学生信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStudent(this.form).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.open = false;
                this.getList();
              } else {
                this.$message({
                  message: response.data.msg,
                  type: "warning",
                });
              }
            });
          } else {
            addStudent(this.form).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.open = false;
                this.getList();
              } else {
                this.$message({
                  message: response.data.msg,
                  type: "warning",
                });
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除学生信息编号为"' + ids + '"的数据项？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delStudent(ids).then((response) => {
            if (response.data.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "warning",
                message: response.data.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
    //查询所有宿舍信息
    loadAllDorm() {
      getAllDormitory().then((response) => {
        this.dormitoryList = response.data.data;
      });
    },
  },
};
</script>
